package com.own.component.common.util.executor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.management.ManagementFactory;

/**
 * ExecutorConfig
 *
 * @author chenxueli
 * @date 2022-12-02 10:02:00
 */
@Slf4j
@SpringBootConfiguration
public class ExecutorConfig {

    public static final String ASYNC_EXECUTOR_NAME = "customAsyncExecutor";

    @Bean(name = ASYNC_EXECUTOR_NAME)
    public ThreadPoolTaskExecutor customAsyncExecutor() {
        log.debug("==========>开始注入线程池 Bean");
        var osBean = ManagementFactory.getOperatingSystemMXBean();
        log.info("==========>CPU 可用核心: {}", osBean.getAvailableProcessors());
        var executor = new ThreadPoolTaskExecutor();
        // for passing in request scope context
        // 线程上下文拷贝实现类
        executor.setTaskDecorator(new ContextCopyingDecorator());
        executor.setCorePoolSize(osBean.getAvailableProcessors() + 1);
        executor.setMaxPoolSize(osBean.getAvailableProcessors() + 1);
        executor.setQueueCapacity(100);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix("cat-");
        executor.initialize();
        return executor;
    }

}
